package com.itheima.health.controller.idem;

import com.itheima.health.common.MessageConst;
import com.itheima.health.util.AliOsssUtil;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.result.PageResult;
import com.itheima.health.result.QueryPageBean;
import com.itheima.health.result.Result;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AliOsssUtil aliOsssUtil;

    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        log.info("[套餐项-分页查询]data:{}", queryPageBean);
        //rpc查询数据
        PageResult pageResult = setmealService.pageQuery(queryPageBean);
        //封装返回结果
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, pageResult);
    }

    /**
     * 新增套餐
     * @param checkgroupIds 检查组ids
     */
    @PostMapping("/add")
    public Result addSetmeal(@RequestParam List<Integer> checkgroupIds,
                             @RequestBody Setmeal setmeal){
        log.info("[套餐-新增套餐]:{}", setmeal);
        setmealService.add(checkgroupIds, setmeal);
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        //原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //根据.来截取文件名称，截取.往后的文件名称包括.
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机生成一个36位的文件名称并且和截取到的原始文件名后缀拼接
        String name = UUID.randomUUID().toString() + substring;
        log.info("文件上传: {}", name);
        try {
            String filePath = aliOsssUtil.upload(imgFile.getBytes(), name);
            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS,filePath);
        } catch (IOException e) {
            log.error("文件上传失败");
        }
        return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
    }
}


